package deustotech.mobility.vc.core;

import c2x.japi.net.messages.Message;
import c2x.japi.net.messages.MessageListener;
import c2x.japi.net.messages.ipMessages.ipMessage;
import c2x.japi.net.messages.ipMessages.ipMessageParser;
import c2x.japi.threads.SendReceiveThread;

public class UnicastListener extends Thread implements MessageListener {
	private static UnicastListener instance;
	private SendReceiveThread SRT;
	private Controller c;
	private int IPv4Port = 1500;
	private String dir;
	private ServidorUniCast sUC;
	private boolean on = true;


	public static UnicastListener getInstance() { 
		
		if(instance == null)
			instance = new UnicastListener();
		return instance;
		
	}
	public void run(){
		System.out.println("Listener Launched");
		try {
			c = Controller.getInstance();
			SRT = new SendReceiveThread(c.getGateway().getHostAddress(), (short)IPv4Port,(short)IPv4Port,new ipMessageParser());
			SRT.addMessageListener(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void messageReceived(Message msg) {
		System.out.println("nuevo mensaje recibido! "+msg.getPayload());
		if(msg instanceof ipMessage){
			if (msg.getPort() == IPv4Port && on ) {
				if(msg.getHost() == dir){
					Long arriveTime = System.currentTimeMillis();
					byte[] a = msg.getPayload();
					String texto="";
					for(int i=0; i<a.length; i++){
						texto =texto+(char)a[i];
						System.out.print((char)a[i]);
					}
					if(texto.startsWith("100")){
						System.out.println("Es un mensaje 100");
						texto = texto.replace("100 enviando ","");
						int num = Integer.parseInt(texto);
						sUC.addReceived(num, arriveTime);
//						receiver.put(num, arriveTime);
					}

				}
			}else
				System.out.println("Msg but not IPv4 || on = off");
		}

	}

	public void apuntarServidor(ServidorUniCast servidorUniCast) {
		dir = servidorUniCast.getDir();
		sUC = servidorUniCast;
		on = true;	
	}

	public void terminate() {
		SRT.removeMessageListener(this);
		SRT.terminate();
		
	}

}
